<?php
/*
 * @See Clu_Db_Table_Abstract
 */
class ads_Model_Ads extends Zend_Db_Table_Abstract
{
    //only specify the table name, everything else inherits
	protected $_name = "ads";
	protected $_primary = "id";

	public function findByPrimary($id)
	{
		if (!$id)
            return null;
        else
		    return $this->fetchRow('id = ' . $this->getAdapter()->quote($id, 'INTEGER'));
	}
	
	public function insertRaw($data, $doValidate = false)
	{
		if ($doValidate)
		{
			//TODO: Validate the Data here
		}
	    $a = array();
	    $a['name'] 		= $data['name'];
	    $a['keywords'] 		= $data['keywords'];
//	    $a['business_category'] 		= $data['business_category'];
//	    $a['created_time'] 		= $this->stringToTime($data['created_time']);
//	    $a['target_continent'] 		= $data['target_continent'];
//	    $a['target_country'] 		= $data['target_country'];
	    $a['type'] = $data['type'];
        $a['text'] 	= $data['text'];
        //$a['action_url'] 	= $data['action_url'];
        $a['link_to'] 	= $data['link_to'];
        $a['user_configurable'] 	= $data['user_configurable'];

	    if (isset($data['languages']))
		    $a['languages'] 		= implode(',', $data['languages']);
		else 
			$a['languages'] 		= 'en';
		
	    if (isset($data['themes']))
		    $a['themes'] 		= implode(',', $data['themes']);
		else 
			$a['themes'] 		= Zend_Registry::get('configuration')->general->defaultTheme;
		
	    if (isset($data['roles']))
		    $a['roles'] 		= ',' . implode(',', $data['roles']) .',';
		else 
			$a['roles'] 		= '';
		/*	
	    if (isset($data['modules']))
		    $a['modules'] 		= implode(',', $data['modules']);
		else 
			$a['modules'] 		= '';
		*/
		$pos = array();
		;
		if($data['region'] && $data['region'] != 'all')
			$pos['region'] = $data['region'];
			
		if($data['weight'] && $data['weight'] != 'all')
			$pos['weight'] = $data['weight'];
			
		if($data['template'] && $data['template'] != 'all')
			$pos['template'] = implode(',', $data['template']);
		
		$a['metadata'] = serialize($pos);		
		
	    $this->insert($a);
	}
	
	public function getAdsData($id)
	{
		if (!$b = $this->findByPrimary($id))
		{
			return null;
		}
		return $b;
	}
	
	public function saveRaw($a, $data, $id, $doValidate)
	{
		$saveData = $data;
	    if ((!$a) && (!$id))
	    	return false;
	    else if (!$a)
	       	if (!$a = $this->findByPrimary($id))
	       		return false;

		if (isset($data['languages']))
			$saveData['languages'] = implode(',', $data['languages']);
		
		if (isset($data['themes']))
			$saveData['themes'] = implode(',', $data['themes']);
		
        if (isset($data['roles']))
			$saveData['roles'] = ',' . implode(',', $data['roles']) . ',';
		
		$pos = array();
		$metadata = unserialize($a->metadata);
		if($data['region'] && $data['region'] != 'all')
			$pos['region'] = $data['region'];
		elseif(isset($metadata['region']))
			$pos['region'] = $metadata['region'];
			
		if($data['weight'] && $data['weight'] != 'all')
			$pos['weight'] = $data['weight'];
		elseif(isset($metadata['weight']))
			$pos['weight'] = $metadata['weight'];
		
		if($data['template'] && $data['template'] != 'all')
			$pos['template'] = implode(',', $data['template']);
		elseif(isset($metadata['template']))
			$pos['template'] = implode(',', $metadata['template']);
				
		$saveData['metadata'] = serialize($pos);
	    if ($doValidate)
	    {
	    	//Validate Data here
	    }
	    $a->setFromArray($saveData);
        return $a->save();
	}

	/**
	 * $data['status']: New status to update ('published','unpublished', 'deleted', 'queued')
	 * $data['statuschange_reason']: Why the status needs to be changed
	 */
	public function bulkUpdateStatus($idArray, $data)
	{
		$idList = implode (',', $idArray);
		$db = $this->getAdapter() ;
        $db->beginTransaction();
        try {
            $sql = "UPDATE articles SET status = ".$db->quote($data['status'],'STRING').", statuschange_reason = ".$db->quote($data['statuschange_reason'], 'STRING')." WHERE id IN (".$idList.")" ;
            $db->query($sql);
            $db->commit();
			return true;
        }    
        catch (Exception $e)
        {
            $db->rollBack();
            return false;
        }   	
    
	}
	
	/**
	 * $idArray:: Array of primary keys
	 * @param $atomic::Boolean whether or not to perform the delete atomically
	 */
	public function deleteByPrimary($idArray, $atomic = true)
	{
        $db = $this->getAdapter();
        if ($atomic)
	        $db->beginTransaction(); //@NOTE: no effect with MyISAM
        try
        {
            $sql1 = "DELETE FROM ads WHERE id IN (". $db->quote($idArray, 'INTEGER') .")" ;
           	$db->query($sql1);
           	if ($atomic)
	            $db->commit();
            return true;
    	}
        catch (Exception $e)
        {
            if ($atomic)
	            $db->rollBack();
            return false;
        }
	}

	/**
	 * Implements Clu_Db_Table_Abstract::search()
	 * @param $data:
	 * 		$data['status']: 'all', 'published', 'queued', 'unpublished' or 'deleted'
	 *      $data['category']: category ID (int)
	 *      $data['languageOperator']: 'none', 'origin', 'been_translated', 'not_translated'
	 *      $data['language']: 'all', 'en', 'vi', 'cn', 'jp'
	 * 
	 * TODO 
	 * 		
	 * 		$data['poster_id'] : poster_id = $data['poster_id']
	 * 		$data['translator_id'] 
	 * 
	 * 		$data['titleOperator'] = 'none', 'contains', 'not_contains', 'equal'
	 * 		$data['titleTextType'] = 'literal', 'regex'
	 *      $data['title']: String
	 *      $datat['titleLanguage']: 'en', 'vn', 'cn', 'jp', 'all'
	 * 		
	 * 
	 * 		$data['bodyOperator'] = 'none', 'contains', 'not_contains'
	 * 		$data['bodyTextType']: 'literal', 'regex'
	 * 		$data['body']: String 
	 * 		$data['bodyLanguage']: 'en', 'vn', 'cn', 'jp', 'all'
	 * 
	 * 		$data['posttimeOperator']: 'none', 'before', 'after', 'between'
	 *      $data['posttime1'] : Integer 
	 *      $data['posttime2'] : Integer: Only relavent in case $data['updatetimeOperator'] === 'between' 

	 * 		$data['updatetimeOperator']: 'none', 'before', 'after', 'between'
	 *      $data['updatetime1'] : Integer 
	 *      $data['updatetime2'] : Integer: Only relavent in case $data['updatetimeOperator'] === 'between' 
	 * 		
	 * 		$data['keywordsOperator'] = 'none', 'contains', 'not_contains', 'equal'
	 * 		$data['keywordsTextType']: 'literal', 'regex'
	 * 		$data['keywords']: String
	 * 		$data['keywordsLanguage']: 'en', 'vn', 'cn', 'jp', 'all'
	 * 	 
	 * TODO: Maybe move this to translation
	 * 		$data['revisionNrOperator'] = 'none', 'greater', 'less', 'equal'
	 * 		$data['revisionNr']: Integer
     */
	
	public function search($data)
	{
    	$keys = array('id', 'languages', 'name', 'themes', 'roles', 'metadata');
        $t = clu_array_merge($keys, $data);
        
    	// Create the Zend_Db_Select object
    	$db = $this->getAdapter();
    	$select = new Zend_Db_Select($db);
		$select = $db->select();

        // Add a FROM clause
        $select->from( array('b' => 'ads'));//, 
        			   //array('id','name', 'languages', 'themes', 'roles', 'type', 'metadata') );
		
		//languages
    	if($t['languages'] && $t['languages']['0'] != 'all')
    	{
    	    if(count($t['languages']) > 1)
        	{
            	$languages = implode(',', $t['languages']);
        	 	$s = "b.languages LIKE " . $db->quoteinto("'%$languages%'","STRING");
        	 	foreach($t['languages'] as $v )
        	 	{
        	 		$s .= " OR b.languages LIKE " . $db->quoteinto("'%$v%'","STRING");
        	 	}
        	 	$select->where($s);
        	 }
        	 else
             { 
            	$languages = $t['languages']['0'];
	        	$select->where('b.languages LIKE ?',$db->quoteinto("%$languages%","STRING"));
             }
    	}
    	
    	/*
    	//modules
    	if($t['modules'] && $t['modules']['0'] != 'all')
    	{
    	    if(count($t['modules']) > 1)
        	{
            	$modules = implode(',', $t['modules']);
        	 	$s = "b.modules LIKE " . $db->quoteinto("'%$modules%'","STRING");
        	 	foreach($t['modules'] as $v )
        	 	{
        	 		$s .= " OR b.modules LIKE " . $db->quoteinto("'%$v%'","STRING");
        	 	}
        	 	$select->where($s);
        	 }
        	 else
             { 
            	$modules = $t['modules']['0'];
	        	$select->where('b.modules LIKE ?',$db->quoteinto("%$modules%","STRING"));
             }
    	}
    	*/	
		if($t['name'])
		{
			$strName = $t['name'];
        	$select->where('b.name LIKE ?',$db->quoteinto("%$strName%","STRING"));
		}
        
        //ID
        if($t['id'])
		{
			$select->where('b.id =?', (int)$db->quote($t['id'], "INT"));
        }	
        
        //roles
        if($t['roles'])
		{
			if(count($t['roles']) > 1)
        	{
            	$roles = implode(',', $t['roles']);
        	 	$s = "b.roles LIKE " . $db->quoteinto("'%$roles%'","STRING");
        	 	foreach($t['roles'] as $v )
        	 	{
        	 		$s .= " OR b.roles LIKE " . $db->quoteinto("'%$v%'","STRING");
        	 	}
        	 	$select->where($s);
        	 }
        	 else
             { 
            	$roles = $t['roles']['0'];
	        	$select->where('b.roles LIKE ?',$db->quoteinto("%$roles%","STRING"));
             }
        }
        
        $metadata = unserialize($t['metadata']);
        
        /*
        if($t['positions'] == 1)
        {
        	$a = array();
	    	//themes
	    	if(isset($t['themes']) && $t['themes']['0'] != 'all')
	    		$a['themes'] = $t['themes']; 
			else
				$a['themes'] = null;
			
			//region
			if($data['region'] && $data['region'] != 'all')
				$a['region'] = ':' . $data['region'];
			else
				$a['region'] = null;
			//weight
			if($data['weight'] && $data['weight'] != 'all')
				$a['weight'] = ':' . $data['weight'];
			else
				$a['weight'] = null;
			
			if(count($t['themes']) > 1)
			{
				if(isset($data['template']) && $data['template'] != 'all')
				{
					if(count($data['template']) > 1)
					{
						foreach($t['themes'] as $p)
						{
							foreach($data['template'] as $temp)
								$b[] = '{' . $p . ':' . $temp . $a['region'] . $a['weight'] . '}';
							$positions = implode(',', $b);
							$s = "b.positions LIKE " . $db->quoteinto("'%$positions%'","STRING");
							foreach(explode(',', $positions) as $pos)
								$s .= " OR b.positions LIKE " . $db->quoteinto("'%$pos%'","STRING");
						}
					}
					else
					{
						foreach($t['themes'] as $p)
							$b[] = '{' . $p . ':' . $data['template']['0'] . $a['region'] . $a['weight'] . '}';							
						$positions = implode(',', $b);
						$s = "b.positions LIKE " . $db->quoteinto("'%$positions%'","STRING");
						foreach(explode(',', $positions) as $pos)
							$s .= " OR b.positions LIKE " . $db->quoteinto("'%$pos%'","STRING");
					}
				 }
				else
				{
					foreach($t['themes'] as $p)
						$positions = '{' . $p . $a['region'] . $a['weight'] . '}';
					$s = "b.positions LIKE " . $db->quoteinto("'%$positions%'","STRING");
					foreach(explode(',', $positions) as $pos)
						$s .= " OR b.positions LIKE " . $db->quoteinto("'%$pos%'","STRING");
				}
			}
			else
			{
				if(isset($data['template']) && $data['template'] != 'all')
				{
					if(count($data['template']) > 1)
					{
						foreach($data['template'] as $temp)
							$template[] = '{' . $t['themes']['0'] . ':' . $temp . $a['region'] . $a['weight'] . '}';
						$positions = implode(',', $template);
						$s = "b.positions LIKE " . $db->quoteinto("'%$positions%'","STRING");
						foreach(explode(',', $positions) as $pos)
							$s .= " OR b.positions LIKE " . $db->quoteinto("'%$pos%'","STRING");
					}
					else
					{
						$positions = '{' . $t['themes']['0'] . ':' .  $data['template']['0'] . $a['region'] . $a['weight'] . '}';
						$s = "b.positions LIKE " . $db->quoteinto("'%$positions%'","STRING");
					}
				}
				else
				{
					$positions = '{' . $a['themes']['0'] .  $a['region'] . $a['weight'] . '}';
					$s = "b.positions LIKE " . $db->quoteinto("'%$positions%'","STRING");
				}
			}
			$select->where($s);
        }	
		*/
        
//        die_a($select->__toString());
		return $select;
	}


	public function insertRawExternal($data, $doValidate = false)
	{
		if ($doValidate)
		{
			//TODO: Validate the Data here
		}
	    $a = array();
	    if (isset($data['article_language']))
		    $a['language'] 		= $data['article_language'];
		else 
			$a['language'] 		= 'en';
	    $a['title'] 		= $data['article_title'];
	    $a['body'] 			= $data['article_body'];

	    $a['author_name'] 	= "abc";
	    $a['author_email'] 	= "abc@a.com";
	    $a['status'] 		= "published";
	    $a['category'] 		= 1;
	    $a['keywords'] 		= "abc";
	    $a['allow_comment'] = 1;
	    
	    $a['poster_id'] 	= 0;
        $a['post_time'] 	= time();
	    return $this->insert($a);
	}
	
	public function searchBlockList($data)
	{
		$db = $this->getAdapter() ;
		$sql = "SELECT * FROM blocks WHERE 1 ";
		if (isset($data['']))
			$sql .= " AND ".$db->quote($data[], '');
		
		if (isset($data['roles']))
		{
			// roles REGEX ',[1|5|19][,]'
			$regex = sprintf(',[%s],', str_replace(',','|',$data['roles']));
			$sql .= sprintf(" AND roles REGEXP  '%s' ", $regex);
		}
		
		if (isset($data['language']))
		{
			$sql .= " AND (languages LIKE '%all%' OR languages LIKE '%".$data['language']."%')";			
		}
		
		if (isset($data['owner']))
		{
			$sql .= " AND (owner LIKE '".$data['owner']."%' OR owner LIKE '%-1%')";			
		}
		
		if (isset($data['theme']))
		{
			$sql .= " AND (themes LIKE '%all%' OR themes LIKE '%".$data['theme']."%')";			
		}
				
		//die($sql);
				
		if (isset($data['']))
			$sql .= " AND ".$db->quote($data[], '');
			
		if (isset($data['']))
			$sql .= " AND ".$db->quote($data[], '');
		
    	return $db->fetchAll($sql);
    	
	}
	public function getRoleName($data)
	{
		//require_once (APP_PATH.'/modules/user/Model/Role.php');
		$rModel = new user_Model_Role();
		foreach($data as $b)
		{
			$roleNames ='';
			foreach (explode(',',$b['roles']) as $roleId)
			{
				if (!$roleId) continue;
				$r = $rModel->findByPrimary($roleId);
				$roleNames .= ','.$r->rname;
			}	
			$b['roleNames'] = $roleNames;
			$d[] = $b;
		}		
		if(isset($d))
			return $d;
		else
			return null;
	}
}
?>